// 初始化 LeanCloud SDK
const AV = require('leancloud-storage');
AV.init({
    appId: 'xOaoGARlVYzk9aKWq27XUHrG-MdYXbMMI',
    appKey: 'tSR7PJplNntKgD0tIExQUy2d',
    serverURL: 'https://xoaogarl.api.lncldglobal.com'
});

// 创建表并插入数据
async function createTablesAndInsertData() {
    try {
        // 表 1: Order
        const Order = AV.Object.extend('Order');
        const order = new Order();
        order.set({
            orderNo: 'ORD202506280001',
            cargoNo: 'CARGO001',
            senderName: '张三',
            senderPhone: '13812345678',
            senderAddress: '北京市朝阳区XX路',
            receiverName: '李四',
            receiverPhone: '13987654321',
            receiverAddress: '上海市浦东新区XX路',
            cargoType: '电子产品',
            totalQuantity: 100,
            totalVolume: 2.5,
            totalWeight: 500,
            paymentMethod: 2, // 现付
            declaredValue: 10000,
            insuranceFee: 50,
            deliveryFee: 100,
            unloadingFee: 50,
            totalFreight: 2000,
            operator: '王五',
            operatorPhone: '13712345678',
            orderTime: new Date(),
            driverId: null, // 待关联
            driverPhone: '',
            route: '北京-上海',
            vehiclePlate: '京A12345',
            departureStationId: null, // 待关联
            transferStationId: null,
            arrivalStationId: null, // 待关联
            status: 0 // 待处理
        });
        await order.save();
        console.log('Order 数据插入成功');

        // 表 2: Delivery
        const Delivery = AV.Object.extend('Delivery');
        const delivery = new Delivery();
        delivery.set({
            orderId: order,
            cargoNo: 'CARGO001',
            orderNo: 'ORD202506280001',
            receiverName: '李四',
            receiverPhone: '13987654321',
            receiverAddress: '上海市浦东新区XX路',
            senderName: '张三',
            senderPhone: '13812345678',
            senderAddress: '北京市朝阳区XX路',
            cargoType: '电子产品',
            totalQuantity: 100,
            totalVolume: 2.5,
            totalWeight: 500,
            paymentMethod: 2,
            declaredValue: 10000,
            insuranceFee: 50,
            deliveryFee: 100,
            unloadingFee: 50,
            collectOnDelivery: 0
        });
        await delivery.save();
        console.log('Delivery 数据插入成功');

        // 表 3: Receivable
        const Receivable = AV.Object.extend('Receivable');
        const receivable = new Receivable();
        receivable.set({
            orderId: order,
            cargoNo: 'CARGO001',
            orderNo: 'ORD202506280001',
            customerId: null, // 待关联
            orderStatus: 0,
            senderAddress: '北京市朝阳区XX路',
            receiverAddress: '上海市浦东新区XX路',
            settlementStatus: 0,
            settlementTime: null,
            reconciliationStatus: 0,
            reconciliationNo: '',
            totalFreight: 2000,
            deliveryFee: 100,
            unloadingFee: 50,
            returnFee: 0,
            transferFee: 0,
            insuranceFee: 50,
            packingFee: 0,
            otherFee: 0,
            cashPayment: 2000,
            pickupPayment: 0,
            arrivalPayment: 0,
            monthlyPayment: 0,
            payableAmount: 2000,
            reconciledAmount: 0,
            unreconciledAmount: 2000,
            invoiceStatus: 0,
            invoicedAmount: 0,
            uninvoicedAmount: 2000,
            departureStationId: null,
            arrivalStationId: null,
            orderTime: new Date(),
            driverId: null,
            driverPhone: '',
            operator: '王五',
            senderName: '张三',
            senderPhone: '13812345678'
        });
        await receivable.save();
        console.log('Receivable 数据插入成功');

        // 表 4: Reconciliation
        const Reconciliation = AV.Object.extend('Reconciliation');
        const reconciliation = new Reconciliation();
        reconciliation.set({
            reconciliationNo: 'REC202506280001',
            customerId: null,
            totalOrders: 1,
            totalCargoQuantity: 100,
            totalCargoVolume: 2.5,
            totalCargoWeight: 500,
            totalReceivable: 2000,
            totalReceived: 0,
            creator: '王五',
            senderName: '张三',
            senderPhone: '13812345678',
            senderAddress: '北京市朝阳区XX路'
        });
        await reconciliation.save();
        console.log('Reconciliation 数据插入成功');

        // 表 5: Customer - 客户管理
        const Customer = AV.Object.extend('Customer');
        const customers = [
            {
                customerName: '北京科技有限公司',
                customerType: 'enterprise',
                contactPerson: '张经理',
                contactPhone: '13812345678',
                contactEmail: 'zhang@bjtech.com',
                address: '北京市朝阳区科技园区1号楼',
                creditLimit: 100000,
                usedCredit: 25000,
                settlementCycle: '月结30天',
                status: 1,
                remark: '重要客户'
            },
            {
                customerName: '上海贸易公司',
                customerType: 'enterprise',
                contactPerson: '李总',
                contactPhone: '13987654321',
                contactEmail: 'li@shtrade.com',
                address: '上海市浦东新区金融街88号',
                creditLimit: 200000,
                usedCredit: 80000,
                settlementCycle: '月结15天',
                status: 1,
                remark: '长期合作伙伴'
            },
            {
                customerName: '王小明',
                customerType: 'individual',
                contactPerson: '王小明',
                contactPhone: '13612345678',
                contactEmail: 'wang@email.com',
                address: '广州市天河区珠江新城',
                creditLimit: 50000,
                usedCredit: 12000,
                settlementCycle: '现结',
                status: 1,
                remark: '个人客户'
            }
        ];
        
        for (const customerData of customers) {
            const customer = new Customer();
            customer.set(customerData);
            await customer.save();
        }
        console.log('Customer 数据插入成功');

        // 表 6: Driver - 司机管理
        const Driver = AV.Object.extend('Driver');
        const drivers = [
            {
                driverName: '张师傅',
                company: 'XX物流',
                phone: '13812345678',
                idCard: '110101198001011234',
                licenseType: 'A2',
                licenseExpiry: new Date('2025-12-31'),
                qualificationExpiry: new Date('2025-06-30'),
                homeAddress: '北京市朝阳区XX小区',
                emergencyContact: '张太太',
                emergencyPhone: '13812345679',
                status: 1,
                remark: '经验丰富，安全驾驶'
            },
            {
                driverName: '李师傅',
                company: 'XX物流',
                phone: '13987654321',
                idCard: '310101198505051234',
                licenseType: 'B2',
                licenseExpiry: new Date('2026-03-15'),
                qualificationExpiry: new Date('2025-09-20'),
                homeAddress: '上海市浦东新区XX路',
                emergencyContact: '李先生',
                emergencyPhone: '13987654322',
                status: 1,
                remark: '熟悉华东地区路线'
            },
            {
                driverName: '王师傅',
                company: 'XX物流',
                phone: '13612345678',
                idCard: '440101197912121234',
                licenseType: 'A1',
                licenseExpiry: new Date('2024-08-10'),
                qualificationExpiry: new Date('2024-12-25'),
                homeAddress: '广州市天河区XX街',
                emergencyContact: '王女士',
                emergencyPhone: '13612345679',
                status: 0,
                remark: '证件即将到期'
            }
        ];
        
        for (const driverData of drivers) {
            const driver = new Driver();
            driver.set(driverData);
            await driver.save();
        }
        console.log('Driver 数据插入成功');

        // 表 7: Vehicle - 车辆管理
        const Vehicle = AV.Object.extend('Vehicle');
        const vehicles = [
            {
                vehicleNumber: '京A12345',
                vehicleType: 'large_truck',
                driver: '张师傅',
                route: '北京-上海',
                length: 9.6,
                capacity: '2人',
                loadVolume: '40立方米',
                loadWeight: '20吨',
                status: 1
            },
            {
                vehicleNumber: '沪B67890',
                vehicleType: 'medium_truck',
                driver: '李师傅',
                route: '上海-杭州',
                length: 7.2,
                capacity: '2人',
                loadVolume: '30立方米',
                loadWeight: '15吨',
                status: 1
            },
            {
                vehicleNumber: '粤C11111',
                vehicleType: 'small_truck',
                driver: '王师傅',
                route: '广州-深圳',
                length: 4.2,
                capacity: '2人',
                loadVolume: '15立方米',
                loadWeight: '5吨',
                status: 2
            }
        ];
        
        for (const vehicleData of vehicles) {
            const vehicle = new Vehicle();
            vehicle.set(vehicleData);
            await vehicle.save();
        }
        console.log('Vehicle 数据插入成功');

        // 表 8: Station
        const Station = AV.Object.extend('Station');
        const station = new Station();
        station.set({
            code: 'STA001',
            name: '北京站',
            type: 0, // 发货站
            areaCode: '110000',
            manager: '王五',
            phone: '13712345678',
            status: 1 // 启用
        });
        await station.save();
        console.log('Station 数据插入成功');

    } catch (error) {
        console.error('数据插入失败:', error);
    }
}

// 执行建表和插入数据
createTablesAndInsertData();